package ink.metoo.auto.fishpi.chatroom.handler.redpacket

import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.chatroom.ChatRooms
import ink.metoo.auto.fishpi.chatroom.Message
import ink.metoo.auto.fishpi.chatroom.RedPacket

class RockPaperScissorsRedPacketHandler : RedPacketHandler {

    override val types = arrayOf(RedPacket.Type.ROCK_PAPER_SCISSORS)

    override fun handle(message: Message, redPacket: RedPacket) {
        if (message.isMe) {
            return
        }
        val st = Settings.chatRoom.watchRockPaperScissorsMoney
        if (!((st.min..st.max).contains(redPacket.money))) {
            return
        }
        super.handle(message, redPacket)
    }

    override fun receivedStatusHandle(message: Message, redPacket: RedPacket) {
        val whoGot = message.whoGot

        fun Int?.getUserState() = when (this) {
            null -> "未知"
            0 -> "平局"
            else -> if (this > 0) "输了" else "赢了"
        }

        val description = redPacket.typeEnum.description
        val rpMsg = redPacket.msg
        if (whoGot != null) {
            val whoGotReceivedInfo = redPacket.who.findLast { it.userName == whoGot } ?: return
            message.userName = message.whoGive
            message.time = whoGotReceivedInfo.time
            val userMoney = whoGotReceivedInfo.userMoney
            val state = userMoney.getUserState()
            ChatRooms.console(
                message,
                "【${description}】 $rpMsg ${redPacket.money}($state) <${whoGotReceivedInfo.userName}> $userMoney"
            )
        } else {
            val receivedInfo = redPacket.who.map {
                val userMoney = it.userMoney
                val state = userMoney.getUserState()
                return@map "($state) <${it.userName}> $userMoney"
            }.joinToString(", ")
            ChatRooms.console(message, "【${description}】 $rpMsg ${redPacket.money}$receivedInfo")
        }
    }
}